import { Player } from './state'
import Game from './game'
import { Position, Chess } from './map'
import _ from 'lodash'

export default class AIPlayer {
    private player: Player
    private game: Game

    constructor(player: Player, game: Game) {
        this.player = player
        this.game = game
    }

    // 决策树算法选择最佳移动
    makeDecision(): [Position, Position] | null {
        const myPieces = this.getAllMyPieces()
        const possibleMoves: Array<[Position, Position]> = []

        // 收集所有可能的合法移动
        for (const piece of myPieces) {
            const [r, c] = piece.position
            for (let tr = 0; tr < this.game.map.data.length; tr++) {
                for (let tc = 0; tc < this.game.map.data[0].length; tc++) {
                    const targetPos: Position = [tr, tc]
                    if (this.game.checkAction(piece.position, targetPos)) {
                        possibleMoves.push([piece.position, targetPos])
                    }
                }
            }
        }

        if (possibleMoves.length === 0) return null

        // 简单决策树：优先吃子，其次随机移动
        const captureMoves = possibleMoves.filter(([_, targetPos]) => {
            const targetTile = this.game.map.getTile(targetPos)
            return targetTile instanceof Chess && targetTile.player !== this.player
        })

        if (captureMoves.length > 0) {
            // 优先吃价值高的棋子
            return _.sample(captureMoves) ?? _.sample(possibleMoves) ?? null
        }

        return _.sample(possibleMoves) ?? null
    }

    private getAllMyPieces(): Array<{position: Position, value: number}> {
        const pieces: Array<{position: Position, value: number}> = []
        for (let r = 0; r < this.game.map.data.length; r++) {
            for (let c = 0; c < this.game.map.data[0].length; c++) {
                const tile = this.game.map.getTile([r, c])
                if (tile instanceof Chess && tile.player === this.player) {
                    pieces.push({
                        position: [r, c],
                        value: this.getPieceValue(tile.surface)
                    })
                }
            }
        }
        return pieces
    }

    private getPieceValue(surface: string): number {
        const values: Record<string, number> = {
            '将': 1000, '帅': 1000,
            '车': 9, '炮': 5, '马': 4,
            '士': 2, '仕': 2,
            '象': 2, '相': 2,
            '兵': 1, '卒': 1
        }
        return values[surface] || 1
    }
}
